define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/vips/models'),
        utils = require('js/utils/tools'),
        moment = require('moment'),
        app = Backbone.history;
    require('datetimepicker');
    require('multiselect');
    require('magnific');

    var ActiveVipsListView = Backbone.View.extend({
        events: {
            'click #search': 'doSearch',
            'change #selectAll': 'selectAll',
            'change .check-row': 'checkRow',
            'click #export': 'exportData',
        },

        initialize: function (options) {
            this.options = options;
            this.collection = new models.ActiveVipsCollection();
            this.checkedUids = [];
            this.collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        exportData: function () {
            notify.warning('警告', '导出中，请等待');
            utils.exportData(this.collection.url, this._getSearchOption());
        },
        selectAll: function (e) {
            var checked = $(e.target).is(':checked');
            $('.check-row').prop('checked', checked);
            if (!checked) {
                this.checkedUids = [];
            } else {
                this.checkedUids = this.collection.pluck('uid');
            }
            $('#selectTips').html('已选中' + this.checkedIds.length + '个');
        },
        checkRow: function (e) {
            var tr = $(e.target).closest('tr'),
                uid = tr.data('uid');
            if ($(e.target).is(':checked')) {
                this.checkedUids.push(uid);
            } else {
                this.checkedUids = _.without(this.checkedUids, uid);
            }
            $('#selectTips').html('已选中' + this.checkedUids.length + '个');
        },
        _getSearchOption: function () {
            var options = utils.getAllInput('#sidebar_right', true),
                searched = utils.getAllInput('#sidebar_right');
            searched.visit_status = parseInt($('#searchVisitStatus').val());
            searched.add_status = parseInt($('#searchAddStatus').val());
            if (searched.visit_status != -1 || searched.add_status != -1) {
                options.status = 0;
                if (searched.visit_status != -1) options.status |= searched.visit_status;
                if (searched.add_status != -1) options.status |= searched.add_status;
            }
            options.$size = -1;
            utils.saveSearched('vips/active', searched);
            return options;
        },
        doSearch: function () {
            var options = this._getSearchOption();
            app.navigate(utils.composeQueryString('#vips/active/', options), {
                trigger: true
            });
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('vips/active')
            }));
            var that = this;
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#vips/active/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('.date-input').datetimepicker({
                format: 'YYYY-MM-DD'
            });
            utils.multiselect('#inputStatus');
            $('#updateStatus').magnificPopup({
                items: {
                    src: '#updateStatusPannel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                disableOn: function () {
                    return that.checkedUids.length > 0;
                },
                callbacks: {
                    beforeOpen: function () {
                        $('#submitUpdateStatus').off('click').click(function () {
                            $.magnificPopup.close();
                            var status = $('#inputStatus').val(),
                                final = 0;
                            _.each(status, function (s) {
                                final |= s;
                            })
                            $.post(that.collection.url, JSON.stringify({
                                ids: that.checkedUids,
                                status: final
                            })).fail(function (data) {
                                notify.notifyResp(data);
                            }).then(function (data) {
                                notify.success();
                                that.collection.fetch({
                                    reset: true,
                                    data: that.options
                                })
                                that.checkedUids = [];
                            });
                        });
                    },

                }
            });
            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                    $('#content').append('<h4 class="text-muted">无数据</h4>');
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "vips/ActiveVips.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            if (!this.options.created_at) this.options.created_at = moment().format('YYYY-MM-DD');
            var view = new ActiveVipsListView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});